<template>
    <div class="page-container">
        <!-- Nav Tabs -->
        <div class="nav-card">
            <el-tabs
                v-model="activeTab"
                class="account-tabs"
                @tab-click="(tab) => handleTabChange(tab.paneName)"
            >
                <el-tab-pane label="企业账号" name="enterprise">
                    <!-- Enterprise Account Content -->
                    <div class="account-content">
                        <!-- Search Card -->
                        <div class="search-card">
                            <div class="card-header">
                                <span class="card-title">查询条件</span>
                            </div>
                            <div class="search-section">
                                <el-form
                                    :inline="true"
                                    :model="enterpriseQueryParams"
                                    class="query-form"
                                >
                                    <el-form-item label="用户名">
                                        <el-input
                                            v-model="enterpriseQueryParams.username"
                                            placeholder="请输入用户名"
                                            clearable
                                            class="custom-input"
                                            style="width: 200px"
                                        />
                                    </el-form-item>
                                    <el-form-item label="状态">
                                        <el-select
                                            v-model="enterpriseQueryParams.status"
                                            placeholder="请选择状态"
                                            clearable
                                            class="custom-select"
                                            style="width: 120px"
                                        >
                                            <el-option label="正常" :value="0" />
                                            <el-option label="停用" :value="1" />
                                        </el-select>
                                    </el-form-item>
                                    <div class="form-actions">
                                        <el-button
                                            @click="resetEnterpriseQuery"
                                            class="btn-secondary"
                                            round
                                            >重置</el-button
                                        >
                                        <el-button
                                            type="primary"
                                            @click="queryEnterpriseAccounts"
                                            class="btn-primary-theme"
                                            round
                                            >查询</el-button
                                        >
                                        <el-button
                                            type="success"
                                            class="btn-success-theme"
                                            round
                                            :loading="enterpriseActionLoading"
                                            @click="openCreateEnterpriseDialog"
                                            >创建账号</el-button
                                        >
                                    </div>
                                </el-form>
                            </div>
                        </div>

                        <!-- Table Card -->
                        <div class="table-card">
                            <div class="card-header">
                                <span class="card-title">企业账号列表</span>
                                <span class="section-subtitle"
                                    >共
                                    <span class="highlight-num">{{ enterpriseTotal }}</span>
                                    条记录</span
                                >
                            </div>
                            <el-table
                                :data="enterpriseTableData"
                                :loading="enterpriseLoading"
                                style="width: 100%"
                                class="modern-table"
                                :header-cell-style="{
                                    background: '#f8fafc',
                                    color: '#475569',
                                    fontWeight: '700',
                                    fontSize: '13px',
                                    height: '56px',
                                    textAlign: 'center',
                                }"
                                :cell-style="{ textAlign: 'center', padding: '12px 0' }"
                            >
                                <el-table-column
                                    prop="username"
                                    label="用户名"
                                    min-width="160"
                                    align="center"
                                >
                                    <template #default="{ row }">
                                        <span class="cell-primary-text">{{ row.username }}</span>
                                    </template>
                                </el-table-column>

                                <el-table-column
                                    prop="enterpriseId"
                                    label="企业ID"
                                    width="200"
                                    align="center"
                                >
                                    <template #default="{ row }">
                                        <span class="cell-text font-mono">{{
                                            row.enterpriseId
                                        }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="enterpriseName"
                                    label="企业名称"
                                    min-width="180"
                                    show-overflow-tooltip
                                    align="left"
                                >
                                    <template #default="{ row }">
                                        <span class="cell-text">{{ row.enterpriseName }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="status"
                                    label="状态"
                                    width="120"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <div
                                            class="status-badge"
                                            :class="
                                                scope.row.status === 0
                                                    ? 'status-success'
                                                    : 'status-danger'
                                            "
                                        >
                                            <span class="status-dot"></span>
                                            {{ scope.row.status === 0 ? '正常' : '停用' }}
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="createdAt"
                                    label="创建时间"
                                    width="180"
                                    align="center"
                                >
                                    <template #default="{ row }">
                                        <span class="timestamp-text">{{ row.createdAt }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="操作"
                                    width="150"
                                    fixed="right"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-button
                                            size="small"
                                            link
                                            :type="scope.row.status === 0 ? 'danger' : 'success'"
                                            class="action-btn"
                                            :class="scope.row.status === 0 ? 'danger' : 'success'"
                                            :loading="enterpriseActionLoading"
                                            @click="toggleEnterpriseStatus(scope.row)"
                                        >
                                            {{ scope.row.status === 0 ? '停用' : '启用' }}
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <div class="pagination-wrapper">
                                <el-pagination
                                    v-model:current-page="enterpriseQueryParams.pageNo"
                                    v-model:page-size="enterpriseQueryParams.pageSize"
                                    :page-sizes="[10, 20, 50, 100]"
                                    layout="total, sizes, prev, pager, next, jumper"
                                    :total="enterpriseTotal"
                                    @size-change="handleEnterpriseSizeChange"
                                    @current-change="handleEnterpriseCurrentChange"
                                />
                            </div>
                        </div>
                    </div>
                </el-tab-pane>

                <el-tab-pane label="市账号" name="city">
                    <!-- City Account Content -->
                    <div class="account-content">
                        <div class="search-card">
                            <div class="card-header">
                                <span class="card-title">查询条件</span>
                            </div>
                            <div class="search-section">
                                <el-form :inline="true" :model="cityQueryParams" class="query-form">
                                    <el-form-item label="用户名">
                                        <el-input
                                            v-model="cityQueryParams.username"
                                            placeholder="请输入用户名"
                                            clearable
                                            class="custom-input"
                                            style="width: 200px"
                                        />
                                    </el-form-item>
                                    <el-form-item label="状态">
                                        <el-select
                                            v-model="cityQueryParams.status"
                                            placeholder="请选择状态"
                                            clearable
                                            class="custom-select"
                                            style="width: 120px"
                                        >
                                            <el-option label="正常" :value="0" />
                                            <el-option label="停用" :value="1" />
                                        </el-select>
                                    </el-form-item>
                                    <div class="form-actions">
                                        <el-button
                                            @click="resetCityQuery"
                                            class="btn-secondary"
                                            round
                                            >重置</el-button
                                        >
                                        <el-button
                                            type="primary"
                                            @click="queryCityAccounts"
                                            class="btn-primary-theme"
                                            round
                                            >查询</el-button
                                        >
                                        <el-button
                                            type="success"
                                            class="btn-success-theme"
                                            round
                                            :loading="cityActionLoading"
                                            @click="openCreateCityDialog"
                                            >创建账号</el-button
                                        >
                                    </div>
                                </el-form>
                            </div>
                        </div>

                        <div class="table-card">
                            <div class="card-header">
                                <span class="card-title">市账号列表</span>
                                <span class="section-subtitle"
                                    >共
                                    <span class="highlight-num">{{ cityTotal }}</span> 条记录</span
                                >
                            </div>
                            <el-table
                                :data="cityTableData"
                                :loading="cityLoading"
                                style="width: 100%"
                                class="modern-table"
                                :header-cell-style="{
                                    background: '#f8fafc',
                                    color: '#475569',
                                    fontWeight: '700',
                                    fontSize: '13px',
                                    height: '56px',
                                    textAlign: 'center',
                                }"
                                :cell-style="{ textAlign: 'center', padding: '12px 0' }"
                            >
                                <el-table-column
                                    prop="username"
                                    label="用户名"
                                    min-width="160"
                                    align="center"
                                >
                                    <template #default="{ row }">
                                        <span class="cell-primary-text">{{ row.username }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="cityCode"
                                    label="市编码"
                                    width="120"
                                    align="center"
                                >
                                    <template #default="{ row }">
                                        <span class="cell-text font-mono">{{ row.cityCode }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="市名称" min-width="150" align="center">
                                    <template #default="scope">
                                        <span class="cell-text">{{
                                            cityOptions[scope.row.cityCode - 1]?.label || '-'
                                        }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="status"
                                    label="状态"
                                    width="120"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <div
                                            class="status-badge"
                                            :class="
                                                scope.row.status === 0
                                                    ? 'status-success'
                                                    : 'status-danger'
                                            "
                                        >
                                            <span class="status-dot"></span>
                                            {{ scope.row.status === 0 ? '正常' : '停用' }}
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="createdAt"
                                    label="创建时间"
                                    width="180"
                                    align="center"
                                >
                                    <template #default="{ row }">
                                        <span class="timestamp-text">{{ row.createdAt }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="操作"
                                    width="150"
                                    fixed="right"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-button
                                            size="small"
                                            link
                                            :type="scope.row.status === 0 ? 'danger' : 'success'"
                                            class="action-btn"
                                            :class="scope.row.status === 0 ? 'danger' : 'success'"
                                            :loading="cityActionLoading"
                                            @click="toggleCityStatus(scope.row)"
                                        >
                                            {{ scope.row.status === 0 ? '停用' : '启用' }}
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <div class="pagination-wrapper">
                                <el-pagination
                                    v-model:current-page="cityQueryParams.pageNo"
                                    v-model:page-size="cityQueryParams.pageSize"
                                    :page-sizes="[10, 20, 50, 100]"
                                    layout="total, sizes, prev, pager, next, jumper"
                                    :total="cityTotal"
                                    @size-change="handleCitySizeChange"
                                    @current-change="handleCityCurrentChange"
                                />
                            </div>
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>

        <!-- Create Enterprise Dialog -->
        <el-dialog
            v-model="showCreateEnterpriseDialog"
            title="创建企业账号"
            width="600px"
            class="custom-dialog"
            align-center
            :before-close="() => (showCreateEnterpriseDialog = false)"
        >
            <el-form
                ref="enterpriseFormRef"
                :model="enterpriseForm"
                label-position="top"
                class="modern-form"
            >
                <el-form-item label="组织机构代码">
                    <el-input
                        v-model="enterpriseForm.enterpriseInfo.orgCode"
                        placeholder="请输入组织机构代码"
                        class="custom-input"
                    />
                </el-form-item>

                <el-form-item label="所属地区">
                    <el-cascader
                        v-model="regionValue"
                        :options="regionOptions"
                        :props="{ label: 'name', value: 'code', children: 'children' }"
                        placeholder="请选择地区"
                        @change="handleRegionChange"
                        clearable
                        class="custom-select"
                        style="width: 100%"
                    />
                </el-form-item>

                <el-form-item label="企业名称">
                    <el-input
                        v-model="enterpriseForm.enterpriseInfo.name"
                        placeholder="请输入企业名称"
                        class="custom-input"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showCreateEnterpriseDialog = false" class="btn-secondary"
                        >取消</el-button
                    >
                    <el-button
                        type="primary"
                        class="btn-primary-theme"
                        :loading="enterpriseActionLoading"
                        @click="createEnterpriseAccount"
                        >确定</el-button
                    >
                </div>
            </template>
        </el-dialog>

        <!-- Create City Dialog -->
        <el-dialog
            v-model="showCreateCityDialog"
            title="创建市账号"
            width="500px"
            class="custom-dialog"
            align-center
            :before-close="() => (showCreateCityDialog = false)"
        >
            <el-form
                ref="cityFormRef"
                :model="cityForm"
                :rules="cityRules"
                label-position="top"
                class="modern-form"
            >
                <el-form-item label="州市选择" prop="cityCode">
                    <el-select
                        v-model="cityForm.cityCode"
                        placeholder="请选择州市"
                        @change="handleCitySelectChange"
                        class="custom-select"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="city in cityOptions"
                            :key="city.value"
                            :label="city.label"
                            :value="city.value"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showCreateCityDialog = false" class="btn-secondary"
                        >取消</el-button
                    >
                    <el-button
                        type="primary"
                        class="btn-primary-theme"
                        :loading="cityActionLoading"
                        @click="createCityAccount"
                        >确定</el-button
                    >
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import {
    ElCard,
    ElAlert,
    ElTabs,
    ElTabPane,
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElButton,
    ElTable,
    ElTableColumn,
    ElTag,
    ElPagination,
    ElDialog,
    ElMessage,
    ElMessageBox,
} from 'element-plus';
import accountApi from '../../api/account.js';
// 导入地区、企业性质和行业的数据
import regionData from '../../dict/yunnan_region_code.json';

// 当前激活的标签页
const activeTab = ref('enterprise');

// 地区、企业性质和行业的数据
const regionOptions = ref(regionData);

// 地区级联选择的响应式数据
const regionValue = ref([]);

// 处理地区选择变化
const handleRegionChange = (values) => {
    regionValue.value = values;
    // 使用最后一级的地区编码作为region值
    enterpriseForm.enterpriseInfo.region =
        values.length > 0 ? values[values.length - 1] : undefined;
};

// 企业账号相关数据
const enterpriseAccountsData = ref([]);
const enterpriseTotal = ref(0);
const enterpriseTableData = computed(() => {
    const list = enterpriseAccountsData.value || [];
    const size = enterpriseQueryParams.value.pageSize || 10;
    const page = enterpriseQueryParams.value.pageNo || 1;
    if (list.length <= size) return list;
    const start = (page - 1) * size;
    return list.slice(start, start + size);
});
const enterpriseQueryParams = ref({
    pageNo: 1,
    pageSize: 10,
    username: '',
    status: undefined,
    enterpriseId: '',
});
const showCreateEnterpriseDialog = ref(false);
const enterpriseLoading = ref(false); // 企业账号加载状态
const enterpriseActionLoading = ref(false); // 企业账号操作加载状态

// 企业账号表单数据
const enterpriseForm = reactive({
    username: '',
    password: '',
    enterpriseInfo: {
        orgCode: '',
        name: '',
        region: undefined,
    },
});

// 企业表单引用
const enterpriseFormRef = ref();

// 打开创建企业账号对话框
const openCreateEnterpriseDialog = () => {
    // 重置表单
    if (enterpriseFormRef.value) {
        enterpriseFormRef.value.resetFields();
    }
    // 清空表单数据
    enterpriseForm.username = '';
    enterpriseForm.password = '';

    // 清空企业基本信息
    enterpriseForm.enterpriseInfo.name = '';

    // 清空所有可选企业信息字段
    enterpriseForm.enterpriseInfo.orgCode = '';
    enterpriseForm.enterpriseInfo.region = undefined;

    // 重置级联选择框的值
    regionValue.value = [];

    // 显示对话框
    showCreateEnterpriseDialog.value = true;
};

// 创建企业账号
const createEnterpriseAccount = async () => {
    if (!enterpriseFormRef.value) return;

    try {
        await enterpriseFormRef.value.validate();

        // 显示操作加载状态
        enterpriseActionLoading.value = true;

        // 调用API创建企业账号
        const params = {
            type: 1,
            username: enterpriseForm.username,
            password: enterpriseForm.password,
            enterpriseInfo: {
                orgCode: enterpriseForm.enterpriseInfo.orgCode,
                region: enterpriseForm.enterpriseInfo.region,
                name: enterpriseForm.enterpriseInfo.name,
            },
        };

        await accountApi.createAccount(params);

        ElMessage.success('企业账号创建成功');
        showCreateEnterpriseDialog.value = false;

        // 重新加载企业账号列表
        await loadEnterpriseAccounts();
    } catch (error) {
        if (error === false) {
            // 表单验证失败
            return;
        }
        console.error('创建企业账号失败:', error);
        const errorMessage =
            error?.response?.data?.message || error?.message || '创建企业账号失败，请重试';
        ElMessage.error(errorMessage);
    } finally {
        // 关闭操作加载状态
        enterpriseActionLoading.value = false;
    }
};

// 打开创建市账号对话框
const openCreateCityDialog = () => {
    // 重置表单
    if (cityFormRef.value) {
        cityFormRef.value.resetFields();
    }
    // 清空表单数据
    cityForm.cityCode = undefined; // 使用undefined而非空字符串，符合验证规则的数字类型要求
    cityForm.cityName = '';
    // 显示对话框
    showCreateCityDialog.value = true;
};

// 处理州市选择变化
const handleCitySelectChange = (value) => {
    const selectedCity = cityOptions.value.find((city) => city.value === value);
    if (selectedCity) {
        cityForm.cityName = selectedCity.label;
    }
};

// 创建市账号
const createCityAccount = async () => {
    if (!cityFormRef.value) return;

    try {
        await cityFormRef.value.validate();

        // 显示操作加载状态
        cityActionLoading.value = true;

        // 调用API创建市账号
        const params = {
            type: 2, // 市账号类型
            username: cityForm.username,
            password: cityForm.password,
            cityCode: cityForm.cityCode, // 传递选择的州市编码
        };

        await accountApi.createAccount(params);

        ElMessage.success('市账号创建成功');
        showCreateCityDialog.value = false;

        // 重新加载市账号列表
        await loadCityAccounts();
    } catch (error) {
        if (error === false) {
            // 表单验证失败
            return;
        }
        console.error('创建市账号失败:', error);
        const errorMessage =
            error?.response?.data?.message || error?.message || '创建市账号失败，请重试';
        ElMessage.error(errorMessage);
    } finally {
        // 关闭操作加载状态
        cityActionLoading.value = false;
    }
};

// 州市数据列表
const cityOptions = ref([
    { label: '临沧市', value: 1 },
    { label: '丽江市', value: 2 },
    { label: '保山市', value: 3 },
    { label: '大理白族自治州', value: 4 },
    { label: '德宏傣族景颇族自治州', value: 5 },
    { label: '怒江傈僳族自治州', value: 6 },
    { label: '文山壮族苗族自治州', value: 7 },
    { label: '昆明市', value: 8 },
    { label: '昭通市', value: 9 },
    { label: '普洱市', value: 10 },
    { label: '曲靖市', value: 11 },
    { label: '楚雄彝族自治州', value: 12 },
    { label: '玉溪市', value: 13 },
    { label: '红河哈尼族彝族自治州', value: 14 },
    { label: '西双版纳傣族自治州', value: 15 },
    { label: '迪庆藏族自治州', value: 16 },
]);

// 市账号相关数据
const cityAccountsData = ref([]);
const cityTotal = ref(0);
const cityTableData = computed(() => {
    const list = cityAccountsData.value || [];
    const size = cityQueryParams.value.pageSize || 10;
    const page = cityQueryParams.value.pageNo || 1;
    if (list.length <= size) return list;
    const start = (page - 1) * size;
    return list.slice(start, start + size);
});
const cityQueryParams = ref({
    pageNo: 1,
    pageSize: 10,
    username: '',
    status: undefined,
    cityCode: '',
});
const showCreateCityDialog = ref(false);
const cityLoading = ref(false); // 市账号加载状态
const cityActionLoading = ref(false); // 市账号操作加载状态

// 市账号表单数据
const cityForm = reactive({
    username: '',
    password: '',
    cityCode: '',
    cityName: '',
});

// 市表单验证规则
const cityRules = {
    cityCode: [
        { required: true, message: '请选择州市', trigger: 'blur' },
        { type: 'number', message: '州市选择无效', trigger: 'blur' },
    ],
};

// 市表单引用
const cityFormRef = ref();

// 标签页切换时加载对应数据
const handleTabChange = (tab) => {
    if (tab === 'city') {
        loadCityAccounts();
    } else if (tab === 'enterprise') {
        loadEnterpriseAccounts();
    }
};

// 加载企业账号列表
const loadEnterpriseAccounts = async () => {
    try {
        // 显示加载状态
        enterpriseLoading.value = true;

        const response = await accountApi.loadAllEnterpriseAccount(enterpriseQueryParams.value);
        enterpriseAccountsData.value = response.data?.list || [];
        enterpriseTotal.value = response.data?.totalCount ?? response.data?.total ?? 0;
    } catch (error) {
        console.error('加载企业账号失败:', error);
        const errorMessage =
            error?.response?.data?.message || error?.message || '加载企业账号失败，请重试';
        ElMessage.error(errorMessage);
        // 错误时清空数据，避免显示旧数据
        enterpriseAccountsData.value = [];
        enterpriseTotal.value = 0;
    } finally {
        // 关闭加载状态
        enterpriseLoading.value = false;
    }
};

// 查询企业账号
const queryEnterpriseAccounts = () => {
    enterpriseQueryParams.value.pageNo = 1;
    loadEnterpriseAccounts();
};

// 重置企业账号查询
const resetEnterpriseQuery = () => {
    enterpriseQueryParams.value = {
        pageNo: 1,
        pageSize: 10,
        username: '',
        status: undefined,
        enterpriseId: '',
    };
    loadEnterpriseAccounts();
};

// 分页大小变化
const handleEnterpriseSizeChange = (size) => {
    enterpriseQueryParams.value.pageSize = size;
    loadEnterpriseAccounts();
};

// 当前页码变化
const handleEnterpriseCurrentChange = (current) => {
    enterpriseQueryParams.value.pageNo = current;
    loadEnterpriseAccounts();
};

// 切换企业账号状态
const toggleEnterpriseStatus = async (row) => {
    try {
        const newStatus = row.status === 0 ? 1 : 0;
        const action = newStatus === 0 ? '启用' : '停用';

        // 弹出确认对话框
        await ElMessageBox.confirm(`确定要${action}账号「${row.username}」吗？`, '操作确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            customClass: 'custom-message-box',
            confirmButtonClass: 'btn-primary-theme',
            cancelButtonClass: 'btn-secondary',
        });

        // 显示操作加载状态
        enterpriseActionLoading.value = true;

        // 调用API修改状态
        await accountApi.changeStatus({
            username: row.username,
            status: newStatus,
        });

        // 更新本地状态
        row.status = newStatus;
        ElMessage.success(`${action}成功`);
    } catch (error) {
        if (error === 'cancel') {
            // 用户取消操作
            return;
        }
        console.error('修改账号状态失败:', error);
        const errorMessage =
            error?.response?.data?.message || error?.message || '修改账号状态失败，请重试';
        ElMessage.error(errorMessage);
    } finally {
        // 关闭操作加载状态
        enterpriseActionLoading.value = false;
    }
};

// 加载市账号列表
const loadCityAccounts = async () => {
    try {
        // 显示加载状态
        cityLoading.value = true;

        const response = await accountApi.loadAllCityAccount(cityQueryParams.value);
        cityAccountsData.value = response.data?.list || [];
        cityTotal.value = response.data?.totalCount ?? response.data?.total ?? 0;
    } catch (error) {
        console.error('加载市账号失败:', error);
        const errorMessage =
            error?.response?.data?.message || error?.message || '加载市账号失败，请重试';
        ElMessage.error(errorMessage);
        // 错误时清空数据，避免显示旧数据
        cityAccountsData.value = [];
        cityTotal.value = 0;
    } finally {
        // 关闭加载状态
        cityLoading.value = false;
    }
};

// 查询市账号
const queryCityAccounts = () => {
    cityQueryParams.value.pageNo = 1;
    loadCityAccounts();
};

// 重置市账号查询
const resetCityQuery = () => {
    cityQueryParams.value = {
        pageNo: 1,
        pageSize: 10,
        usernameFuzzy: '',
        status: undefined,
        cityCode: '',
    };
    loadCityAccounts();
};

// 分页大小变化
const handleCitySizeChange = (size) => {
    cityQueryParams.value.pageSize = size;
    loadCityAccounts();
};

// 当前页码变化
const handleCityCurrentChange = (current) => {
    cityQueryParams.value.pageNo = current;
    loadCityAccounts();
};

// 切换市账号状态
const toggleCityStatus = async (row) => {
    try {
        const newStatus = row.status === 0 ? 1 : 0;
        const action = newStatus === 0 ? '启用' : '停用';

        // 弹出确认对话框
        await ElMessageBox.confirm(`确定要${action}账号「${row.username}」吗？`, '操作确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            customClass: 'custom-message-box',
            confirmButtonClass: 'btn-primary-theme',
            cancelButtonClass: 'btn-secondary',
        });

        // 显示操作加载状态
        cityActionLoading.value = true;

        // 调用API修改状态
        await accountApi.changeStatus({
            username: row.username,
            status: newStatus,
        });

        // 更新本地状态
        row.status = newStatus;
        ElMessage.success(`${action}成功`);
    } catch (error) {
        if (error === 'cancel') {
            // 用户取消操作
            return;
        }
        console.error('修改账号状态失败:', error);
        const errorMessage =
            error?.response?.data?.message || error?.message || '修改账号状态失败，请重试';
        ElMessage.error(errorMessage);
    } finally {
        // 关闭操作加载状态
        cityActionLoading.value = false;
    }
};

// 初始加载企业账号数据
onMounted(() => {
    loadEnterpriseAccounts();
});
</script>

<style scoped lang="scss">
.page-container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    padding: 24px 40px;
    color: #1e293b;
    font-family: 'Inter', sans-serif;
}

/* Header */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 40px;
    background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
    border-radius: 24px;
    color: white;
    box-shadow: 0 20px 40px -12px rgba(79, 70, 229, 0.3);
}

.page-title {
    font-size: 28px;
    font-weight: 800;
    margin: 0 0 8px 0;
    color: white;
}

.page-description {
    font-size: 15px;
    opacity: 0.9;
    margin: 0;
    font-weight: 400;
    color: white;
}

/* Nav Tabs */
.nav-card {
    background: white;
    border-radius: 16px;
    padding: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;
    border: 1px solid #f1f5f9;
    display: flex;
    justify-content: flex-start;
}

.account-tabs {
    width: 100%;
    
    :deep(.el-tabs__header) {
        margin: 0;
        border-bottom: none;
    }

    :deep(.el-tabs__nav-wrap) {
        &::after {
            display: none;
        }
    }

    :deep(.el-tabs__nav) {
        border: none;
        background: #f1f5f9;
        padding: 4px;
        border-radius: 12px;
        display: flex;
        gap: 8px;
    }

    :deep(.el-tabs__item) {
        border: none;
        margin: 0;
        padding: 8px 24px !important;
        height: auto;
        line-height: 1.5;
        border-radius: 8px;
        color: #64748b;
        font-weight: 600;
        transition: all 0.2s ease;

        &.is-active {
            background-color: #ffffff;
            color: #4f46e5;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        }

        &:hover:not(.is-active) {
            color: #475569;
            background-color: rgba(255, 255, 255, 0.5);
        }
    }

    :deep(.el-tabs__active-bar) {
        display: none;
    }
}

/* Search Card */
.search-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02);
    margin-bottom: 24px;
    border: 1px solid rgba(241, 245, 249, 1);
    overflow: hidden;
}

.card-header {
    padding: 16px 24px;
    border-bottom: 1px solid #f1f5f9;
    background: #fafafa;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-title {
    font-size: 15px;
    font-weight: 700;
    color: #0f172a;
}

.search-section {
    padding: 24px;
}

.query-form {
    margin-bottom: 0;
    display: flex;
    flex-wrap: wrap;
    gap: 24px;
    align-items: flex-end;

    :deep(.el-form-item) {
        margin-bottom: 0;
        margin-right: 0;
        display: flex;
        flex-direction: column;

        .el-form-item__label {
            justify-content: flex-start;
            padding-bottom: 6px;
            font-size: 13px;
            font-weight: 600;
            color: #64748b;
        }
    }
}

.form-actions {
    display: flex;
    gap: 12px;
    margin-left: auto;
    align-self: flex-end;
}

/* Table Card */
.table-card {
    background: #ffffff;
    border-radius: 24px;
    box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.03);
    border: 1px solid rgba(241, 245, 249, 1);
    overflow: hidden;
    margin-bottom: 24px;
}

.section-subtitle {
    font-size: 13px;
    color: #64748b;

    .highlight-num {
        color: #4f46e5;
        font-weight: 700;
        font-size: 15px;
        padding: 0 2px;
    }
}

/* Modern Table */
.modern-table {
    border-radius: 16px;
    overflow: hidden;
    --el-table-border-color: #f1f5f9;
    --el-table-row-hover-bg-color: #f8fafc;
    --el-table-header-bg-color: #f8fafc;
}

.cell-primary-text {
    font-size: 14px;
    font-weight: 600;
    color: #0f172a;
}

.cell-text {
    font-size: 13px;
    color: #64748b;
}

.font-mono {
    font-family: 'JetBrains Mono', monospace;
}

.timestamp-text {
    font-variant-numeric: tabular-nums;
    color: #334155;
    font-size: 13px;
    font-weight: 500;
}

/* Status Badges */
.status-badge {
    display: inline-flex;
    align-items: center;
    padding: 4px 12px;
    border-radius: 99px;
    font-size: 12px;
    font-weight: 600;
    line-height: 1.5;
}

.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 8px;
}

.status-success {
    background: #ecfdf5;
    color: #059669;
    .status-dot {
        background: #10b981;
    }
}
.status-danger {
    background: #fef2f2;
    color: #dc2626;
    .status-dot {
        background: #ef4444;
    }
}

/* Buttons */
.btn-primary-theme {
    background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 600;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.25);
    transition: all 0.2s ease;
    padding: 8px 20px;
}

.btn-primary-theme:hover {
    background: linear-gradient(135deg, #4338ca 0%, #4f46e5 100%) !important;
    transform: translateY(-1px);
    box-shadow: 0 8px 20px rgba(79, 70, 229, 0.35);
}

.btn-success-theme {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 600;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.25);
    transition: all 0.2s ease;
    padding: 8px 20px;
}

.btn-success-theme:hover {
    background: linear-gradient(135deg, #059669 0%, #047857 100%) !important;
    transform: translateY(-1px);
    box-shadow: 0 8px 20px rgba(16, 185, 129, 0.35);
}

.btn-secondary {
    background: #fff;
    border: 1px solid #e2e8f0;
    color: #475569;
    font-weight: 500;
    border-radius: 8px;
    padding: 8px 20px;

    &:hover {
        background: #f8fafc;
        color: #1e293b;
        border-color: #cbd5e1;
    }
}

.action-btn {
    font-weight: 600;
    &.success {
        color: #10b981;
        &:hover {
            color: #059669;
        }
    }
    &.danger {
        color: #ef4444;
        &:hover {
            color: #dc2626;
        }
    }
}

.pagination-wrapper {
    padding: 16px 24px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #f1f5f9;
}

/* Inputs */
.custom-input,
.custom-select {
    :deep(.el-input__wrapper) {
        border-radius: 8px;
        box-shadow: 0 0 0 1px #e2e8f0 inset;
        padding: 6px 12px;
        &.is-focus {
            box-shadow: 0 0 0 2px #818cf8 inset;
        }
    }
}

/* Dialog */
:deep(.custom-dialog) {
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);

    .el-dialog__header {
        margin: 0;
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;
        .el-dialog__title {
            font-weight: 700;
            font-size: 18px;
            color: #0f172a;
        }
    }

    .el-dialog__body {
        padding: 32px;
    }

    .el-dialog__footer {
        padding: 20px 24px;
        border-top: 1px solid #f1f5f9;
        background-color: #f8fafc;
    }
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.modern-form {
    :deep(.el-form-item__label) {
        font-weight: 600;
        color: #475569;
        margin-bottom: 8px;
    }
}
</style>

<style lang="scss">
/* Global styles for ElMessageBox */
.custom-message-box {
    border-radius: 16px !important;
    overflow: hidden;
    border: none !important;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important;
    padding-bottom: 20px !important;

    .el-message-box__header {
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;

        .el-message-box__title {
            font-weight: 700;
            color: #0f172a;
        }
    }

    .el-message-box__content {
        padding: 24px;
        color: #334155;
        font-size: 15px;
    }

    .el-message-box__btns {
        padding: 0 24px 0 0;

        .el-button {
            border-radius: 8px;
            font-weight: 600;
            padding: 10px 20px;
            height: auto;
        }

        .btn-primary-theme {
            background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
            border: none;
            color: white;

            &:hover {
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
            }
        }

        .btn-secondary {
            background: #fff;
            border: 1px solid #e2e8f0;
            color: #475569;

            &:hover {
                background: #f8fafc;
                color: #1e293b;
            }
        }
    }
}
</style>
